package chapter5.section6;

/**
 * 程序5-16：利用匿名内部类实现排序
 */

import java.util.Arrays;
import java.util.Comparator;

public class Account {
    private final String id;
    private final String name;
    private final int balance;

    public Account(String id, String name, int balance) {
        super();
        this.id = id;
        this.name = name;
        this.balance = balance;
    }

    public static void main(String[] args) {
        Account[] accounts = new Account[5];
        accounts[0] = new Account("001", "王峰", 1000);
        accounts[1] = new Account("002", "张静", 1500);
        accounts[2] = new Account("003", "鲁宁", 800);
        accounts[3] = new Account("004", "翟宇", 660);
        accounts[4] = new Account("005", "刘新", 1700);
        //下面利用Arrays的sort方法进行排序，需要一个比较器对象
        Arrays.sort(accounts, new Comparator<Account>() {
            @Override
            public int compare(Account o1, Account o2) {
                int result = 0;
                if (o1.getBalance() > o2.getBalance()) {
                    result = 1;
                } else if (o1.getBalance() == o2.getBalance()) {
                    result = 0;
                } else {
                    result = -1;
                }
                return result;
            }

        });
        for (int i = 0; i < accounts.length; i++) {
            System.out.println(accounts[i]);
        }
    }

    public int getBalance() {
        return balance;
    }

    @Override
    public String toString() {
        return "Account[id:" + id + ",name:" + name + ",balance:" + balance + "]";
    }
}
